import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnChanges
} from "@angular/core";
import { NzNotificationService } from "ng-zorro-antd";
import { HttpServcie } from "../../../../service/http.service";
import { ElevatorInfoBean } from "../bean/elevatorInfo.bean";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from "@angular/forms";
import { Observable } from "rxjs/Rx";
import { FileUploader, FileItem, ParsedResponseHeaders } from "ng2-file-upload";
import { Config } from "../../../../service/config";
import * as moment from "moment";
import { elevatorPlaces } from "../../../../service/constant/elevatorPlaceConstant";
@Component({
  selector: "elevator-modify",
  templateUrl: "elevator-modify.html",
  styleUrls: ["elevator-modify.scss"]
})
/**
 * 电梯信息修改
 */
export class ElevatotModifyPage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  functions: any = [];
  expandDataCache = {};
  @Input()
  inValue: any = {};
  data:any = [];
  @Output("outPut")
  outPut = new EventEmitter();
  //电梯信息
  elevatorlnfoBean: ElevatorInfoBean = new ElevatorInfoBean();
  //电梯添加的权限(功能)
  funList: any = [];

  //机构的集合
  partyList: any = [];
  //省市区
  options: any = [];
  //地址
  addresOptions: any = [];
  //电梯类型
  elevatorTypeOptions: any = [];
  //物业
  wuyeList: any = [];
  //维保
  weibaoList: any = [];
  // 检验
  jianyanList: any = [];
  // 监管
  jianguanList: any = [];
  // 检验人员
  jianyanren: any = [];
  //安全管理人员
  anquanList: any = [];
  //维保人员
  weibaoren: any = [];
  // 电梯场所类型
  elevatorPlaces = elevatorPlaces;
  // 分局类型id重新绑定  --- 转化为nubmer类型
  public branchOfficeId:any;

  // 电梯地址三个字段拼接
  elevatorAddress:string="";


  initCheckDate: any;
  showImage: any = [];
  config: any = Config;
  fileUploader = new FileUploader({
    url: Config.IP + Config.API.upload,
    method: "POST",
    itemAlias: "file",
    autoUpload: false,
    headers: [
      { name: "Authorization", value: "Bearer " + window.localStorage["token"] }
    ]
  });

  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService
  ) { }

  /**
   * 选择checkbox
   * @param event
   * @param param
   */
  refreshStatus(event, param) {
    if (event) {
      this.funList.push(param);
    } else {
      //如果非选中状态移除
      if (this.funList.length > 0) {
        this.httpServcie.removeByValue(this.funList, param);
      }
    }
  }
  ngOnInit() {
    this.branchOfficeId = parseInt(this.elevatorlnfoBean.branchOffice);
    let partyTypeId = JSON.parse(window.localStorage.getItem("user")).partyType;
    let parentId = "";
    if (partyTypeId == "4") {
      parentId = JSON.parse(window.localStorage.getItem("user")).partyId;
    } else {
      parentId = JSON.parse(window.localStorage.getItem("user")).partyParentId;
    }

    //查询需要的数据
    Observable.forkJoin(
      //查询电梯类型
      this.httpServcie.queryelevatorTypeList(),
      //查询当前用户所属机构下的物业机构
      this.httpServcie.queryByIdAndTypeList({ partyType: 2 }),
      //查询当前用户所属机构下的维保
      this.httpServcie.queryByIdAndTypeList({ partyType: 1, id: parentId}),//使用单位父级单位下的维保单位
      //查询检测机构
      this.httpServcie.queryByIdAndTypeList({ partyType: 3 }),
      //查询监管机构
      this.httpServcie.queryByIdAndTypeList({ partyType: 4,  id: parentId }) //修改成当前
    ).subscribe(data => {
      if (data[0].status == 200) {
        this.elevatorTypeOptions = data[0].data.list;
        
      }
      if (data[1].status == 200) {
        //物业机构
        this.wuyeList = data[1].data;
      }
      if (data[2].status == 200) {
        //维保机构
        this.weibaoList = data[2].data;
      }
      if (data[3].status == 200) {
        //检验机构
        this.jianyanList = data[3].data;
      }
      if (data[4].status == 200) {
        //监管机构
        this.jianguanList = data[4].data;
      }
    });

    this.validateForm = this.fb.group({
      elevatorNum: [null, [Validators.required]],
      serialNum: [null, [Validators.required]],
      addresOptions: [null, [Validators.required]],
      elevatorStreet: [null, [Validators.nullValidator]],
      elevatorAddr: [null, [Validators.nullValidator]],
      elevatorModel: [null, [Validators.nullValidator]],
      elevatorTypeId: [null, [Validators.nullValidator]],
      elevatorPhotoUrl: [null, [Validators.nullValidator]],
      examinationPartyName: [null, [Validators.nullValidator]],
      usedPartyId: [null, [Validators.nullValidator]],
      buildingInfo: [null, [Validators.nullValidator]],
      elevatorBuildingNum: [null, [Validators.nullValidator]],
      createCompanyName: [null, [Validators.nullValidator]],
      examinationPartyId: [null, [Validators.nullValidator]],
      nextCheckDateShow: [null, [Validators.nullValidator]],
      safeUserId: [null, [Validators.nullValidator]],
      maintenanceUserFirst: [null, [Validators.nullValidator]],
      maintenanceUserSecond: [null, [Validators.nullValidator]],
      rescuePhoneNum: [null, [Validators.nullValidator]],
      insuranceNum: [null, [Validators.nullValidator]],
      lastMaintenanceTimeShow: [null, [Validators.nullValidator]],
      isStop: [null, [Validators.nullValidator]],
      nextMaintenanceDateShow: [null, [Validators.nullValidator]],
      pointsNum: [null, [Validators.nullValidator]],
      qrCodeUrl: [null, [Validators.nullValidator]],
      insuranceName: [null, [Validators.nullValidator]],
      insuranceDateShow: [null, [Validators.nullValidator]],
      maintTel: [null, [Validators.nullValidator]],
      nextHalfmonMaintDateShow: [null, [Validators.nullValidator]],
      nextQuarterlyMainteDateShow: [null, [Validators.nullValidator]],
      nextHalfyearMaintDateShow: [null, [Validators.nullValidator]],
      nextYearMaintDateShow: [null, [Validators.nullValidator]],
      outsideNum: [null, [Validators.nullValidator]],
      maintenancePartyId: [null, [Validators.nullValidator]],
      buildAddr: [null, [Validators.nullValidator]],
      usedNum: [null, [Validators.nullValidator]],
      beUsedDateShow: [null, [Validators.nullValidator]],
      governorCkDateShow: [null, [Validators.nullValidator]],
      floorStation: [null, [Validators.nullValidator]],
      safeUserTel: [null, [Validators.nullValidator]],
      buildPartyName: [null, [Validators.nullValidator]],
      ratedLoad: [null, [Validators.nullValidator]],
      runSpeed: [null, [Validators.nullValidator]],
      angle: [null, [Validators.nullValidator]],
      stepWidth: [null, [Validators.nullValidator]],
      liftHeight: [null, [Validators.nullValidator]],
      driveWay: [null, [Validators.nullValidator]],
      brandName: [null, [Validators.nullValidator]],
      elevatorPlace: [null, [Validators.nullValidator]],
      branchOfficeId: [null, [Validators.required]],
      programName: [null, [Validators.nullValidator]],
      lastInspectDateShow: [null, [Validators.nullValidator]],
      innerId: [null, [Validators.nullValidator]],
      examinationUserFirst: [null, [Validators.nullValidator]],
      examinationUserSecond: [null, [Validators.nullValidator]]
    });
  }

  ngOnChanges() {
    if (this.inValue) {
      this.initCheckDate = this.inValue.nextCheckDate;
      let eleValue = Object.assign({}, this.inValue);
      this.elevatorlnfoBean = eleValue;

      // 拼接地址
      if (this.elevatorlnfoBean.elevatorStreet != null && this.elevatorlnfoBean.elevatorStreet != '' && this.elevatorlnfoBean.elevatorStreet != "NULL" ) {
        this.elevatorAddress += this.elevatorlnfoBean.elevatorStreet
      }
      if (this.elevatorlnfoBean.elevatorAddr != null && this.elevatorlnfoBean.elevatorAddr != '' && this.elevatorlnfoBean.elevatorAddr != "NULL") {
        this.elevatorAddress += this.elevatorlnfoBean.elevatorAddr
      }
      if (this.elevatorlnfoBean.buildAddr != null && this.elevatorlnfoBean.buildAddr != '' && this.elevatorlnfoBean.buildAddr != "NULL") {
        this.elevatorAddress += this.elevatorlnfoBean.buildAddr
      }

      //省市区
      let cityList: any = [];
      Config.CITY.forEach(element => {
        if (this.elevatorlnfoBean.elevatorProvince == element.value) {
          cityList.push(element);
        }
        if (this.elevatorlnfoBean.elevatorCity == element.value) {
          cityList.push(element);
        }
        if (this.elevatorlnfoBean.elevatorArea == element.value) {
          cityList.push(element);
        }
      });
      this.addresOptions = cityList;

      //维保人员
      if (
        undefined != this.elevatorlnfoBean.maintenancePartyId &&
        null != this.elevatorlnfoBean.maintenancePartyId
      ) {
        this.httpServcie.queryUserByPartyId(this.elevatorlnfoBean.maintenancePartyId).subscribe(data => {
          if (data.status == 200) {
            this.weibaoren = [];
            if (data.data && data.data.length > 0) {
              data.data.forEach(user => {
                if (user.type == "user" && user.roleId == "7") {
                  this.weibaoren.push(user);
                }
              });
            }
          }
        });
      }

      //安全管理员
      if (
        undefined != this.elevatorlnfoBean.usedPartyId &&
        null != this.elevatorlnfoBean.usedPartyId
      ) {
        this.httpServcie
          .queryUserByPartyId(this.elevatorlnfoBean.usedPartyId)
          .subscribe(data => {
            if (data.status == 200) {
              this.anquanList = [];
              if (data.data && data.data.length > 0) {
                data.data.forEach(user => {
                  if (user.type == "user" && user.roleId == "5") {
                    this.anquanList.push(user);
                  }
                });
              }
            }
          });
      }

      //反显图片
      if (this.elevatorlnfoBean.elevatorPhotoUrl) {
        this.showImage = this.elevatorlnfoBean.elevatorPhotoUrl.split(",");
      }
    }
  }

  submitForm($event, data:any) {
    console.log("--------------------");
    console.log(this.elevatorlnfoBean);
    console.log("--------------------");

    //电梯图片
    /*if (this.elevatorlnfoBean.elevatorPhotoUrl == null || this.elevatorlnfoBean.elevatorPhotoUrl == "") {
      this._notification.create("error", "失败提示", "电梯照片为必输项");
      return false;
    }*/


    // 获取保险有效日期
    if (this.elevatorlnfoBean.insuranceDate != null && this.elevatorlnfoBean.insuranceDate != "") {
      this.elevatorlnfoBean.insuranceDate = moment(this.elevatorlnfoBean.insuranceDate).format('YYYYMMDD');
    }
    // 获取限速器校验日期
    if (this.elevatorlnfoBean.governorCkDate != null && this.elevatorlnfoBean.governorCkDate != "") {
      this.elevatorlnfoBean.governorCkDate = moment(this.elevatorlnfoBean.governorCkDate).format('YYYYMMDD');
    }
    //投用日期
    if (this.elevatorlnfoBean.beUsedDate != null && this.elevatorlnfoBean.beUsedDate != "") {
      this.elevatorlnfoBean.beUsedDate = moment(this.elevatorlnfoBean.beUsedDate).format('YYYYMMDD');
    }
    // 上次维保时间
    if (this.elevatorlnfoBean.lastMaintenanceTime != null && this.elevatorlnfoBean.lastMaintenanceTime != "") {
      this.elevatorlnfoBean.lastMaintenanceTime = moment(this.elevatorlnfoBean.lastMaintenanceTime).format('YYYYMMDD');
    }
    // 上传巡检时间
    if (this.elevatorlnfoBean.lastInspectDate != null && this.elevatorlnfoBean.lastInspectDate != "") {
      this.elevatorlnfoBean.lastInspectDate = moment(this.elevatorlnfoBean.lastInspectDate).format('YYYYMMDD');
    }
    // 下次检验日期
    if (this.elevatorlnfoBean.nextCheckDate != null && this.elevatorlnfoBean.nextCheckDate != "") {
      this.elevatorlnfoBean.nextCheckDate = moment(this.elevatorlnfoBean.nextCheckDate).format('YYYYMMDD');
    }
    if (this.showImage != null) {
      this.elevatorlnfoBean.elevatorPhotoUrl = this.showImage.join(",");
    }

    // 获取省、市、区
    if (this.addresOptions) {
      //省
      this.elevatorlnfoBean.elevatorProvince = this.addresOptions[0];
      //市
      this.elevatorlnfoBean.elevatorCity = this.addresOptions[1];
      //区
      this.elevatorlnfoBean.elevatorArea = this.addresOptions[2];
      if (this.addresOptions[0] != undefined && this.addresOptions[0] != "" && this.addresOptions[0] != null) {
        if (this.addresOptions[0].value) {  //如果修改时候没有 重新选择，则取value
          //省
          this.elevatorlnfoBean.elevatorProvince = this.addresOptions[0].value;
          //市
          this.elevatorlnfoBean.elevatorCity = this.addresOptions[1].value;
          //区
          this.elevatorlnfoBean.elevatorArea = this.addresOptions[2].value;
        }
      }
    }

    // 重点场所
    if (
      undefined != this.elevatorlnfoBean.elevatorPlace &&
      null != this.elevatorlnfoBean.elevatorPlace
    ) {
      if (this.elevatorlnfoBean.elevatorPlace == "其他") {
        this.elevatorlnfoBean.placeType = "非重点场所";
      } else {
        this.elevatorlnfoBean.placeType = "重点场所";
      }
    }
    this.isSpinning = true;
    this.elevatorlnfoBean.branchOffice = this.branchOfficeId.toString();
    //this.elevatorlnfoBean.parentId = JSON.parse(window.localStorage['user']).partyId;
    let users = JSON.parse(window.localStorage.getItem("user"));
    this.elevatorlnfoBean.loggerType = users.partyType;
    this.elevatorlnfoBean.roleId = users.roleId;
    this.elevatorlnfoBean.loggerUserId = users.id;
    let ob = this.httpServcie.elevatorUpdate(this.elevatorlnfoBean);
    ob.subscribe(data => {
      this.isSpinning = false;
      if (data.status == 200) {
        //处理超期检验
        if (this.elevatorlnfoBean.nextCheckDate != this.initCheckDate) {
          let param = {
            elevatorId: this.elevatorlnfoBean.id,
            date: this.initCheckDate
          };
          this.httpServcie.recordOvertimeEle(param).subscribe(data => {
            console.log(data.status);
          });
        }
        this._notification.create("success", "成功提示", "修改成功");
        this.outPut.emit($event);
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  //交验
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  executeArray(items, res: any) {
    items.map(item => {
      if (item.checked) {
        res.push({ name: item.text, id: item.value });
      }
      if (item.childList) {
        this.executeArray(item.childList, res);
      }
    });

    return res;
  }

  collapse(array, data, $event) {
    if ($event === false) {
      if (data.childList) {
        data.childList.forEach(d => {
          const target = array.find(a => a.authorId === d.authorId);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [],
      array = [],
      hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.childList) {
        for (let i = node.childList.length - 1; i >= 0; i--) {
          stack.push({
            ...node.childList[i],
            level: node.level + 1,
            expand: false,
            parent: node
          });
        }
      }
    }

    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[node.authorId]) {
      hashMap[node.authorId] = true;
      array.push(node);
    }
  }

  /** load data async  */
  loadData(e: {
    option: any;
    index: number;
    resolve: Function;
    reject: Function;
  }): void {
    if (e.index === -1) {
      e.resolve(this.httpServcie.getProvince());
      return;
    }

    const option = e.option;
    option.loading = true;
    if (e.index === 0) {
      let values: any = option["value"];
      let valueList = this.httpServcie.getCity(e.option);
      let cities: any = {};
      cities[values] = valueList;

      setTimeout(() => {
        option.loading = false;
        e.resolve(cities[option.value]);
      }, 1);
    }
    if (e.index === 1) {
      let value = option["value"];
      let valueList = this.httpServcie.getRelation(e.option);
      let scenicspots: any = {};
      scenicspots[value] = valueList;
      setTimeout(
        () => {
          option.loading = false;
          e.resolve(scenicspots[option.value]);
        },
        1,
        scenicspots,
        option
      );
    }
  }

  //选择物业信息
  wuyeChange() {
    this.elevatorlnfoBean.safeUserId = null;
    this.anquanList = [];
    if (
      undefined != this.elevatorlnfoBean.usedPartyId &&
      null != this.elevatorlnfoBean.usedPartyId
    ) {
      this.httpServcie
        .queryUserByPartyId(this.elevatorlnfoBean.usedPartyId)
        .subscribe(data => {
          if (data.status == 200) {
            this.anquanList = [];
            if (data.data && data.data.length > 0) {
              data.data.forEach(user => {
                if (user.type == "user" && user.roleId == "5") {
                  this.anquanList.push(user);
                }
              });
            }
          }
        });
    }
  }

  //选择维保
  weibaoChange() {
    this.weibaoren = [];
    this.elevatorlnfoBean.maintenanceUserFirst = null;
    this.elevatorlnfoBean.maintenanceUserSecond = null;
    if (
      undefined != this.elevatorlnfoBean.maintenancePartyId &&
      null != this.elevatorlnfoBean.maintenancePartyId
    ) {
      this.httpServcie
        .queryUserByPartyId(this.elevatorlnfoBean.maintenancePartyId)
        .subscribe(data => {
          if (data.status == 200) {
            this.weibaoren = [];
            if (data.data && data.data.length > 0) {
              data.data.forEach(user => {
                if (user.type == "user" && user.roleId == "7") {
                  this.weibaoren.push(user);
                }
              });
            }
          }
        });
    }
  }

  //选择检验
  jianyanChange() {
    this.jianyanren = [];
    this.elevatorlnfoBean.examinationUserFirst = null;
    this.elevatorlnfoBean.examinationUserSecond = null;
    for (let tmp of this.jianyanList) {
      if (this.elevatorlnfoBean.examinationPartyId == tmp.id) {
        this.elevatorlnfoBean.examinationPartyName = tmp.partyName;
        break;
      }
    }
    if (
      undefined != this.elevatorlnfoBean.examinationPartyId &&
      null != this.elevatorlnfoBean.examinationPartyId
    ) {
      this.httpServcie
        .queryUserByPartyId(this.elevatorlnfoBean.examinationPartyId)
        .subscribe(data => {
          if (data.status == 200) {
            this.jianyanren = [];
            if (data.data && data.data.length > 0) {
              data.data.forEach(user => {
                if (user.type == "user" && user.roleId == "7") {
                  this.jianyanren.push(user);
                }
              });
            }
          }
        });
    }
  }

  //选择文件后调用的方法
  selectedFileOnChanged(event) {
    if (event.target.files[0].type.match("image.*")) {
      //手动上传的
      this.fileUploader.uploadAll();
      this.fileUploader.onSuccessItem = (
        item: FileItem,
        response: string,
        status: number,
        headers: ParsedResponseHeaders
      ) => {
        if (status == 200) {
          //判断是否是图片
          if (item.file.type.match("image.*")) {
            this.showImage.push(JSON.parse(response).data);
            //this.userBean.qualificationsUrl = JSON.parse(response).data;
          } else {
            this._notification.create("warning", "警告提示", "请选择图片类型！");
          }
        }
      };
    } else {
      this.fileUploader.clearQueue();
      this._notification.create("warning", "警告提示", "请选择图片类型！");
    }
  }

  //创建二维码
  createQrcode() {
    if (this.elevatorlnfoBean.qrCodeUrl) {
      this.deleteQrcd();
    }
    this.httpServcie.createQrcode().subscribe(data => {
      if (data.status == 200) {
        this.elevatorlnfoBean.qrCodeUrl = data.data;
      }
    });
  }
  //删除图片
  delete(param) {
    this.httpServcie.deleteUpload(param).subscribe(
      data => {
        if (data.status == 200) {
          this.httpServcie.removeByValue(this.showImage, param);
          //this._notification.create('success', '成功提示', '移除成功');
        } else {
          //this._notification.create('error', '失败提示', data.message);
          return;
        }
      },
      error => { }
    );
  }

  deleteQrcd() {
    this.httpServcie.deleteUpload(this.elevatorlnfoBean.qrCodeUrl).subscribe(
      data => {
        if (data.status == 200) {
          this.elevatorlnfoBean.qrCodeUrl = null;
          //this._notification.create('success', '成功提示', '移除成功');
        } else {
          //this._notification.create('error', '失败提示', data.message);
          return;
        }
      },
      error => { }
    );
  }
}
